﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Home.Haushalt.Lib.Element;
using System.Data;
using System.Globalization;

namespace Home.Haushalt.Lib
{
    /// <summary>
    /// 
    /// </summary>
    public class MonthbalanceCollection
    {
        /// <summary></summary>
        public List<Monthbalance> _items = new List<Monthbalance>();

        /// <summary></summary>
        private DataTable _postenTable;

        /// <summary></summary>
        private DataTable _dateTable;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="postenTable"></param>
        /// <param name="dateTable"></param>
        public MonthbalanceCollection(DataTable postenTable, DataTable dateTable)
        {
            _postenTable = postenTable;
            _dateTable = dateTable;

            //Aktuelle Balance hinzufügen
            //Add(DateTime.Now.Month, DateTime.Now.Year);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public Monthbalance Add(int month, int year)
        {
            Monthbalance monthbalance = _items.Where(item => item.Month.Equals(month) && item.Year.Equals(year)).FirstOrDefault();

            if (monthbalance == default(Monthbalance))
            {
                monthbalance = new Monthbalance(_postenTable, _dateTable, month, year);

                _items.Add(monthbalance);

                DataBind();
            }

            return monthbalance;
        }

        /// <summary>
        /// 
        /// </summary>
        public void DataBind()
        {
            if (!_items.Count.Equals(0))
            {
                //Alle bestehende nicht gespeicherte Termine löschen
                _dateTable.Select(string.Format("{0} = -1", Date.Fields.Id)).ToList().ForEach(row => row.Delete());

                //Neue Termine generieren
                _items.ForEach(monthbalance => monthbalance.DataBind());

                //Berechnungsraumstart finden (frühestes Datum aber nicht früher als aktueller Monat)
                DateTime startDate = _items.Min(item => item.FromDate);
                DateTime currentMonthStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                startDate = startDate > currentMonthStart.AddDays(-1) ? startDate : currentMonthStart;

                //Berechnungsraumende finden
                DateTime endDate = _items.Max(item => item.ToDate);

                //Alle Dates in dem Zeitraum richtig sortiert
                DataRow[] rows = _dateTable.Select(
                    string.Format("{0}>=#{1}# and {0}<=#{2}#", Date.Fields.Posting, startDate.ToString(DateTimeFormatInfo.InvariantInfo), endDate.ToString(DateTimeFormatInfo.InvariantInfo)),
                    string.Format("{0} asc, {1} asc, {2} desc, {3} desc", Date.Fields.Posting, Date.Fields.OpponentId, Date.Fields.SaldotypId, Date.Fields.Summe));

                //Start-Saldo initialisieren
                double saldo = DAO.GetCurrentSaldo();

                _items[0].StartSaldo = saldo;

                //Saldo berechnen
                int lastMonth = _items[0].Month;
                foreach (DataRow row in rows)
                {
                    if (lastMonth != row[Date.Fields.Posting].ToDateTime().Month)
                    {
                        lastMonth = row[Date.Fields.Posting].ToDateTime().Month;
                        Monthbalance mb = _items.Where(item => item.Month.Equals(lastMonth) && item.Year.Equals(row[Date.Fields.Posting].ToDateTime().Year)).FirstOrDefault();
                        if (mb != default(Monthbalance))
                        {
                            mb.StartSaldo = saldo;
                        }
                    }

                    if (row[Date.Fields.Active].ToBool(true))
                    {
                        saldo = saldo + (row[Date.Fields.Summe].ToDouble() * row[Date.Fields.SaldotypId].ToDouble());
                        row[Date.Fields.Saldo] = saldo;
                    }
                    else
                    {
                        row[Date.Fields.Saldo] = DBNull.Value;
                    }
                }
            }
        }


    }
}
